#include "usart_proc.h"
#include "stdio.h"
#include "beep.h"
// #include "delay.h"
#include "systick.h"
#include "RTClock.h"
#include "display.h"


#define USART_REC_LEN  			200  	//????????? 200
uint8_t USART_RX_BUF[USART_REC_LEN];    //????,??USART_REC_LEN???.
uint16_t USART_RX_STA = 0;        //??????	

//???fputc?? 
int fputc(int ch, FILE *f)
{      
	usart_data_transmit(USART0, (uint8_t)ch);
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
    return ch;
} 
void Usart_ProcFunc(void)  //????16?????
{
	uint32_t uCommand;
	while (USART_RX_STA&0x8000)
    {
		uCommand = (USART_RX_BUF[0]<<16)+(USART_RX_BUF[1]<<8)+(USART_RX_BUF[2]);   //????????????
		if(uCommand == 0XA5FF01) //USART_RX_BUF[0][1][2] F1F2F3???
        {
			printf("SKY-1 Reset!\r\n"); //????????
            delay_ms(100);
			
			USART_RX_STA = 0 ;    //?????????????
			NVIC_SystemReset(); // ??
		}
		if(uCommand == 0XA5DADD)
        {
			GetClock();
            printf("Now the time is:%02X-%02X-%02X %02X:%02X:%02X\r\n",
                    c.Year,c.Month ,c.Day,c.Hour,c.Minute,c.Second);  //??????

            USART_RX_STA = 0 ;    //?????????????
			#ifdef SEGLCD
				disp.LcdData(17, 0x01);    // OK
			#endif
			Beep.BeepTwinkle();
            break;
        }
		if(uCommand == 0XA5DACC) //USART_RX_BUF[0][1][2] da55da???????
        {
            c.Year  = USART_RX_BUF[3];
			c.Month = USART_RX_BUF[4];
			c.Day   = USART_RX_BUF[5];
			c.Hour  = USART_RX_BUF[6];
			c.Minute = USART_RX_BUF[7];
			c.Second = USART_RX_BUF[8];

			SetClock(&c);
    
            printf("Time Set OK!\r\n");	
            USART_RX_STA = 0 ;    
		 	#ifdef SEGLCD
				disp.LcdData(17, 0x01);    // OK
			#endif
			Beep.BeepTwinkle();
            break;
        }
	}
	USART_RX_STA = 0 ;
}

void USART0_IRQHandler(void)                //??0??????
{
	uint8_t Res;
	if(RESET != usart_interrupt_flag_get(USART0, USART_INT_FLAG_RBNE))  //????(?????????0x0d 0x0a??)
	{	
		Res =usart_data_receive(USART0);	//????????
		if((USART_RX_STA&0x8000)==0) //?????
		{
			if(USART_RX_STA&0x4000) //????0x0d
			{
				if(Res!=0x0a)	USART_RX_STA=0;//????,????
				else   USART_RX_STA|=0x8000;	//?????
			}
			else  //????0X0D
			{	
				if(Res==0x0d) 
					USART_RX_STA|=0x4000;
				else
				{
					USART_RX_BUF[USART_RX_STA&0X3FFF]=Res ;
					USART_RX_STA++;
					if(USART_RX_STA>(USART_REC_LEN-1))	USART_RX_STA=0; //??????,?????? 
				}		 
			}
		}   		 
	} 
}